package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设置单个白名单号码指令
 */
@Slf4j
public class CmdCodec_PBWL implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.PBWL.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,PBWL,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*TP,2020916012,V4,PBWL,130305,1,13612345678,1,0,5C0F660E,1,130306,A,2233.4233,N,11356.1978,E,0.0,2. 8,030315,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.PBWL.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.PBWL.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String[] paraArr= Arrays.copyOfRange(payloadArr,4,payloadArr.length-10);
        String para="";
        for (int i=1;i<paraArr.length;i++){
            // System.out.println(paraArr[i]);
            if(i==1){
                para=paraArr[i];
            }else{
                para=para+","+paraArr[i];
            }
        }
        int j=4+paraArr.length-1;

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[j+1]);
        properties.put("s",payloadArr[j+2]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[j+3],"lat"));
        properties.put("d",payloadArr[j+4]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[j+5],"lon"));
        properties.put("g",payloadArr[j+6]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[j+7]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[j+8]));
        properties.put("upday", payloadArr[j+9]);
        String trackerStatusHex = payloadArr[j+10];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,PBWL,HHMMSS,wl-num,wl-phone,wl_type,wl_meid,wl_name,wl_pic#
        //例子 1：*TP,2020916012,PBWL,130305,1,13612345678,1,0,5C0F660E,1#
        //例 2：删 除 *TP,2020916012,PBWL,130305,1,,1,0,,1#
        //参数说明：wl-num 白名单编号,取值 1-20，展示的位置，可以设置 20 个白名单号码
        //参数说明：wl-phone 白名单电话号码，如果为空，则表示删除该位置号码
        //参数说明：wl_type 白名单类型，1 表示亲情号，2 表示其他号；允许不填，如果不填写，则必须用,隔开
        //        不再使用，如设备有 5 个按键，那么前 5 个白名单对应 5 个可拨打的亲情号。即 wl_type 可不填。
        //参数说明：wl_meid wl_type 为亲情号的时候传’0’；允许不填，如果不填写，则必须用,隔开。不再使用，传’0’或不填。
        //参数说明：wl_name 展示名字文字（比如小明: 5C0F660E）,使用 UNICODE 编码。允许不填，如果不填写，则必须用,隔开
        //参数说明：wl_pic 显示图片类型，取值 1-7,1 中年男人，2 中年女人，3 老年男人，4 老年女人，5 男童，6 女童，7 默认头 像。允许不填，如果不填写，则必须用,隔开
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String wlNum="";
            if(paramsMap.get("wlNum")!=null && !paramsMap.get("wlNum").equals("")) {
                wlNum=paramsMap.get("wlNum").toString();
            }

            String wlPhone="";
            if(paramsMap.get("wlPhone")!=null && !paramsMap.get("wlPhone").equals("")) {
                wlPhone=paramsMap.get("wlPhone").toString();
            }

            String wlType="";
            if(paramsMap.get("wlType")!=null && !paramsMap.get("wlType").equals("")) {
                wlType=paramsMap.get("wlType").toString();
            }
            String wlMeid="";
            if(paramsMap.get("wlMeid")!=null && !paramsMap.get("wlMeid").equals("")) {
                wlMeid=paramsMap.get("wlMeid").toString();
            }

            String wlName="";
            if(paramsMap.get("wlName")!=null && !paramsMap.get("wlName").equals("")) {
                wlName=paramsMap.get("wlName").toString();
            }

            String wlPic="";
            if(paramsMap.get("wlPic")!=null && !paramsMap.get("wlPic").equals("")) {
                wlPic=paramsMap.get("wlPic").toString();
            }

            String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
            /*StringBuffer sb = new StringBuffer();
            sb.append("*");
            sb.append(zzs);//TODO 需要修改成根据设备动态加载
            sb.append(",");
            sb.append(message.getDeviceId());
            sb.append(",");
            sb.append(CommandEnum.PBWL.name());
            sb.append(",");
            sb.append(time);
            sb.append(",");
            sb.append(wlNum);
            sb.append(",");
            sb.append(wlPhone);
            sb.append(",");
            sb.append(wlType);
            sb.append(",");
            sb.append(wlMeid);
            sb.append(",");
            sb.append(wlName);
            sb.append(",");
            sb.append(wlPic);
            sb.append("#");*/
            ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.PBWL.name()+"_"+time,message.getMessageId(),60*3*1000);
            //return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));

            return SxlMessageUtils.SxlCmd.getInstance()
                .appendAndAddSeparator(zzs)
                .appendAndAddSeparator(message.getDeviceId())
                .appendAndAddSeparator(CommandEnum.PBWL.name())
                .appendAndAddSeparator(time)
                .appendAndAddSeparator(wlNum)
                .appendAndAddSeparator(wlPhone)
                .appendAndAddSeparator(wlType)
                .appendAndAddSeparator(wlMeid)
                .appendAndAddSeparator(wlName)
                .append(wlPic).buildEncodeMessage();

        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }

    }
}
